package com.lx.es.query.test.processor;

import cn.lx.es.query.annotation.SearchProcessor;
import cn.lx.es.query.processor.SearchAnnotationProcessor;
import com.lx.es.query.test.annotation.NotInSearch;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 内置处理器 - 不在列表中搜索处理器
 */
@Component
public class SearchNotInProcessor implements SearchAnnotationProcessor<NotInSearch> {
    @Override
    public void process(NotInSearch annotation, Field field, Object value, BoolQueryBuilder boolQueryBuilder) {
        Collection<?> values = null;
        if (value instanceof String) {
            String str = (String) value;
            if (!str.trim().isEmpty()) {
                values = Arrays.stream(str.split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .collect(Collectors.toList());
            }
        } else if (value instanceof Collection) {
            values = (Collection<?>) value;
        }
        if (values != null && !values.isEmpty()) {
            boolQueryBuilder.mustNot(QueryBuilders.termsQuery(field.getName(), values));
        }
    }
    @Override
    public Class<NotInSearch> getAnnotationType() {
        return NotInSearch.class;
    }
}
